package com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by wcy on 2017\6\28 0028.
 */
public class QQLogin extends Activity {
    private static long sClickTime;
    Tencent mTencent;
    QQLoginListener mQQLoginListener;
    LoadingDialog mLoadingDialog;
    public static void login(Context context) {

        if (!isQQClientAvailable(context)) {
            ToastUtil.showMessage(context, "请安装腾讯QQ客户端");
            return;
        }
        if (UserUtils.isLogin()) {
            return;
        }
        if (System.currentTimeMillis() - sClickTime < 500) {
            return;
        }
        sClickTime = System.currentTimeMillis();
        Intent intent = new Intent(context, QQLogin.class);
            context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoadingDialog = new LoadingDialog(this, "正在加载中");
        mTencent = Tencent.createInstance(getString(R.string.qq_app_id), this);
        if (!mTencent.isSessionValid()) {
            mLoadingDialog.show();
            mTencent.login(this, "get_simple_userinfo", mQQLoginListener = new QQLoginListener());
        } else {
            getQQUserInfo();
        }
        EventBus.getDefault().register(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void handleBindEvent(BindEvent event) {
        mLoadingDialog.dismiss();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * QQ授权登录回调
     */
    class QQLoginListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                Log.i("wcy", "QQ login failed");
                return;
            }
            initOpenidAndToken(jsonResponse);//初始化token
            getQQUserInfo();//获取用户信息
        }
        @Override
        public void onError(UiError uiError) {
            Log.i("wcy", "QQ login failed,code:" + uiError.errorMessage);
            finish();
        }

        @Override
        public void onCancel() {
            finish();
        }
        private void initOpenidAndToken(JSONObject jsonObject) {
            try {
                String openid = jsonObject.getString("openid");
                String token = jsonObject.getString("access_token");
                String expires = jsonObject.getString("expires_in");
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openid);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户信息昵称头像回调
     */
    class QQUserInfoListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                return;
            }
            String imageUrl = jsonResponse.optString("figureurl_qq_2");
            if (TextUtils.isEmpty(imageUrl)) {
                imageUrl = jsonResponse.optString("figureurl_2");
            }
            String nickName = jsonResponse.optString("nickname");
            Log.i("wcy", "imageUrl:" + imageUrl + ",nickname:" + nickName);
            //ToastUtil.showMessage(QQLogin.this, "获取用户信息成功");
            StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME,Constants.NICK_NAME, nickName);
            StorageUtils.setPreference(Xutils.getContext(), Constants.SP_NAME,Constants.HEADER_IMG, imageUrl);
            BindRequestParams params = new BindRequestParams();
            params.openid = mTencent.getOpenId();
            params.access_token = mTencent.getAccessToken();
            params.type = Constants.TYPE_LOGIN_BY_QQ;
            // 和后台服务器绑定
            BindHelper.bind(params);
            finish();
        }

        @Override
        public void onError(UiError uiError) {
            finish();
            ToastUtil.showMessage(QQLogin.this, "uiError" + uiError.errorMessage);
        }

        @Override
        public void onCancel() {
            finish();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mQQLoginListener);
    }

    private void getQQUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            UserInfo mInfo = new UserInfo(QQLogin.this, mTencent.getQQToken());
            mInfo.getUserInfo(new QQUserInfoListener());
        }
    }

    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }
}
